﻿/**

 * Copyright (c) 2015-2016, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OF.DistributeService.Core.Common
{
    public class VesionComparer : IComparer<string>
    {
        public static int CompareVersion(string x, string y)
        {
            if (x == y)
            {
                return 0;
            }

            if (x == null)
            {
                if (y == null)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                if (y == null)
                {
                    return 1;
                }
                else
                {
                    var charArr = '.';
                    var xArray = x.Split(charArr);
                    var yArray = y.Split(charArr);
                    int minLen = Math.Min(xArray.Length, yArray.Length);
                    for (int i1 = 0; i1 < minLen; i1++)
                    {
                        int vX = int.Parse(xArray[i1]);
                        int vY = int.Parse(yArray[i1]);
                        if (vX > vY)
                        {
                            return 1;
                        }
                        else if (vX < vY)
                        {
                            return -1;
                        }
                    }

                    if (xArray.Length > yArray.Length)
                    {
                        return 1;
                    }
                    else if (xArray.Length < yArray.Length)
                    {
                        return -1;
                    }
                    else
                    {
                        return 0;
                    }
                }
            }
        }

        public int Compare(string x, string y)
        {
            return CompareVersion(x, y);
        }
    }

}
